package data

import (
	"context"

	"github.com/go-kratos/kratos/v2/log"

	"gitee.com/danqingzhao/go-dango/apps/user/biz"
	"gitee.com/danqingzhao/go-dango/pkg/proto/settings"
)

type policyRepo struct {
	data *Data
	log  *log.Helper
}

func NewPolicyRepo(data *Data, logHelpers *settings.LogHelpers) biz.PolicyRepo {
	return &policyRepo{data: data, log: logHelpers.Data}
}

func (r *policyRepo) AddPolicies(ctx context.Context, pRules, gRules [][]string) error {
	if err := r.data.Casbin.AddPolicies(pRules); err != nil {
		r.log.WithContext(ctx).Error(err.Error())
		return err
	}
	if err := r.data.Casbin.AddGroupPolicies(gRules); err != nil {
		r.log.WithContext(ctx).Error(err.Error())
		return err
	}
	return nil
}

func (r *policyRepo) RemovePolicies(ctx context.Context, pRules, gRules [][]string) error {
	if err := r.data.Casbin.RemovePolicies(pRules); err != nil {
		r.log.WithContext(ctx).Error(err.Error())
		return err
	}
	if err := r.data.Casbin.RemoveGroupPolicies(gRules); err != nil {
		r.log.WithContext(ctx).Error(err.Error())
		return err
	}
	return nil
}

func (r *policyRepo) SavePolicies(ctx context.Context) error {
	if err := r.data.Casbin.SavePolicies(); err != nil {
		r.log.WithContext(ctx).Error(err.Error())
		return err
	}
	return nil
}
